package com.jessechanrui.template.skeleton.config.aspect;

import com.jessechanrui.template.skeleton.common.constant.CommonConstant;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * 全局日志打印，请求与响应内容
 * @author chenrui
 * @date 2024/1/29
 */
@Slf4j
//@Aspect
//@Component
public class WebLogAspect {
    private final ThreadLocal<Object> requestInfoThreadLocal = new ThreadLocal<>();

    /**Controller路径，打印请求与响应信息*/
    @Pointcut("execution(public * com.jessechanrui.template.skeleton.interfaces.*.http..*.*(..))")
    public void webLog() {
    }

    @Before(value = "webLog()")
    public void doBefore(JoinPoint point) {
        ServletRequestAttributes attributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        log.info("流水号：{}", request.getHeader(CommonConstant.SERIAL_NUMBER));
        log.info("请求地址：{}", request.getRequestURL().toString());
        log.info("请求方法：{}", point.getSignature().getDeclaringTypeName() + "." + point.getSignature().getName());
        log.info("请求参数：{}", Arrays.toString(point.getArgs()));
    }

    @AfterReturning(value = "webLog()", returning = "result")
    public void doAferReturning(Object result) {
        if(result != null){
            log.info("响应结果：{}", result.toString());
        }else{
            log.info("响应结果：null");
        }
        requestInfoThreadLocal.remove();
    }

    @AfterThrowing(value = "webLog()", throwing = "throwable")
    public void doAfterThrowing(Throwable throwable) {
        // 保存异常日志记录
        log.info("响应异常结果：{}", throwable.getMessage());
    }
}
